<script setup lang="ts">
import {onMounted, ref, toRaw, computed} from "vue";
import axios from "axios";
import {ElNotification} from "element-plus";
import {ServerHost, loginUser, orderStatusEnum, paymentEnum} from "@/main.js";
import {Refresh, Search, Timer, Upload} from "@element-plus/icons-vue";
import dayjs from 'dayjs'
import PostOrEditPolicy from "@/components/policyManage/PostOrEditPolicy.vue";
import Color from 'color';
import PostOrEditGoods from "@/components/goodsManage/PostOrEditGoods.vue";

const sellerOrderList = ref([])
const goodsList = ref([])
const userList = ref([])
const isLoadingList = ref(true)
const isEditDialogVisible = ref(false)
const selectedOrder = ref()

// 懒加载商家订单列表
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const loadList = () => {
  console.log("开始获取订单列表")
  axios.get(`${ServerHost}/getSellerOrderList?sellerId=${loginUser.value.id}`)
      .then((res) => {
            if (res.status === 200) {
              sellerOrderList.value = res.data.goodsOrderList;
              goodsList.value = res.data.goodsList;
              userList.value = res.data.userList;
              ElNotification({
                title: '订单获取成功',
                type: 'success',
                position: 'bottom-right',
              })
              console.log(sellerOrderList.value)
              hasLoad.value = true
              isLoadingList.value = false
            } else {
              ElNotification({
                title: '订单获取失败',
                type: 'error',
                position: 'bottom-right',
              })
            }
          }
      )
}

const filterTableData = computed(() =>
    sellerOrderList.value.filter(order => {
      return order.id.includes(searchKey.value)
    })
)

// const onEditPolicy = (id: string) => {
//   console.log(id)
// }

const onRowClick = (row: any, column: any, event: Event) => {
  isEditDialogVisible.value = true

  // selectedPolicy.value = policyList.value.find((Policy: any) => {
  //   return Policy.id === row.id
  // })
  sellerOrderList.value.forEach((policy: any) => {
    if (policy.id === row.id) {
      // 深拷贝policy，防止子组件修改父组件数据
      selectedOrder.value = structuredClone(toRaw(policy))
      console.log(selectedOrder.value)
    }
  })
}

// watch(policyList, (newValue, oldValue) => {
//   console.log("数据变化了", newValue, oldValue);
// }, { deep: true });


const getIsSubmitDone = (value: string) => {
  isEditDialogVisible.value = !value
  loadList()
}

const searchKey = ref("")

const onSearchKeydown = (event: KeyboardEvent) => {
  if (event.key === "Enter") {
    // onSearch()
  }
}

const onSearch = () => {
  if (searchKey.value !== "") {
    // loadList()
  }
}

const onClearSearch = (id: string) => {
  // loadList()
}

const isAddDialogVisible = ref(false)
const expressOrder = ref()

const onClickOrderStatus = (e: Event, row: any) => {
  // 阻止冒泡，防止点击表格行时触发onRowClick事件
  e.stopPropagation()
  expressOrder.value = row.row
  const status = row.row.status
  if (status === orderStatusEnum["待发货"]) {
    console.log("发货")
    isExpressDialogVisible.value = true
  } else if (status === orderStatusEnum["待收货"]) {
    ElNotification({
      title: '等待买家收货',
      type: 'info',
      position: 'bottom-right',
    })
  } else if (status === orderStatusEnum["待评价"]) {
    ElNotification({
      title: '等待买家评价',
      type: 'info',
      position: 'bottom-right',
    })
  } else if (status === orderStatusEnum["已完成"]) {
    ElNotification({
      title: '订单已完成',
      type: 'info',
      position: 'bottom-right',
    })
  }
}

const submitExpress = () => {
  if (!expressNum.value) {
    ElNotification({
      title: '请填写快递单号',
      type: 'warning',
      position: 'bottom-right',
    })
    return
  }
  axios.post(`${ServerHost}/updateOrderStatus?id=${expressOrder.value.id}&to=1&expressNum=${expressNum.value}`)
      .then((res) => {
        if (res.status === 200 && res.data.result === 'ok') {
          ElNotification({
            title: '发货成功',
            type: 'success',
            position: 'bottom-right',
          })
          isExpressDialogVisible.value = false
          loadList()
        } else {
          ElNotification({
            title: '发货失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
  console.log(expressOrder.value.id)
  console.log(expressNum.value)
}

const isExpressDialogVisible = ref(false)
const expressNum = ref('')

const statusColor = {
  "待发货": "warning",
  "待收货": "primary",
  "待评价": "info",
  "已完成": "success",
}

</script>

<template>
  <div ref="observerDiv"/>
  <!--  忽略warn type="search" -->
  <div class="flex">
    <el-input type="text" v-model="searchKey" @keydown="onSearchKeydown" class="mb-2 mr-3"
              placeholder="输入名称、ID来搜索产品"
              :prefix-icon="Search" clearable @clear="onClearSearch">
      <template #append>
        <el-button :icon="Search" @click="onSearch"/>
      </template>
    </el-input>

    <el-button @click="isAddDialogVisible = true">
      <el-icon class="el-icon--left">
        <Upload/>
      </el-icon>
      上架商品
    </el-button>

    <el-button @click="loadList">
      <el-icon class="el-icon--left">
        <Refresh/>
      </el-icon>
      刷新列表
    </el-button>
  </div>

  <el-tag class="w-full">点击产品以编辑</el-tag>
  <!--  Table-->
  <!-- height: 减去导航栏、页脚、搜索栏等元素的高度 -->
  <el-table
      :data="filterTableData"
      height="calc(100vh - 120px - 140px)"
      empty-text="没有订单"
      v-loading="isLoadingList"
      :onRowClick="onRowClick">

    <el-table-column
        prop="id"
        label="订单ID">
      <template #default="row">
        <p class="id">{{ row.row.id.split('-')[4] }}</p>
      </template>
    </el-table-column>

    <el-table-column
        prop="buyer_id"
        label="下单产品">
      <template #default="row">
        <p class="">{{ (goodsList.find(goods => goods.id === row.row.goodsId)).name }}</p>
      </template>
    </el-table-column>

    <el-table-column
        prop="buyer_id"
        label="下单用户">
      <template #default="row">
        <p class="">{{ (userList.find(user => user.id === row.row.buyerId)).username }}</p>
      </template>
    </el-table-column>

    <el-table-column
        prop="status"
        label="订单状态">
      <template #default="row">
        <el-button :type="statusColor[Object.keys(orderStatusEnum)[row.row.status]]" @click="onClickOrderStatus($event, row)" class="">{{
            Object.keys(orderStatusEnum)[row.row.status]
          }}
        </el-button>
      </template>
    </el-table-column>
    <el-table-column
        prop="payMethod"
        label="支付方式"
    >
      <template #default="row">
        <p class="">{{ paymentEnum[row.row.payMethod] }}</p>
      </template>
    </el-table-column>
  </el-table>

  <!-- Edit Dialog -->
  <el-dialog
      v-model="isEditDialogVisible"
      title="编辑商品"
      width="500">
    <PostOrEditGoods type="edit" @getValue="getIsSubmitDone" :goods="selectedOrder"
                     :key="selectedOrder"/>
  </el-dialog>

  <!-- Add Dialog -->
  <el-dialog
      v-model="isAddDialogVisible"
      title="上架商品"
      width="500">
    <PostOrEditGoods type="new"/>
  </el-dialog>

  <!-- 发货 Dialog -->
  <el-dialog
      v-model="isExpressDialogVisible"
      title="发货">
    <div class="flex flex-col gap-2">
      <el-tag>订单ID：{{ expressOrder.id }}</el-tag>
      <el-card shadow="never" class="flex flex-col gap-0.5">
        <p>{{ expressOrder.province }} {{ expressOrder.city }} {{ expressOrder.districtAndCounty }}</p>
        <p>{{ expressOrder.address }}</p>
        <p>{{ expressOrder.receiver }} {{ expressOrder.tel }}</p>
      </el-card>
      <el-input v-model="expressNum" placeholder="请填写快递单号">
        <template #prepend>快递单号</template>
      </el-input>
      <el-button @click="submitExpress">确认发货</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-table .el-table.row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.id {
  font-size: 0.7rem;
}
</style>
